import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken, setTokenByName, removeTokenByName, getTokenByName } from '@/utils/auth'
import { resetRouter } from '@/router'
import { getCookie, setCookie } from '@/utils/utilc'
import { loginHXY } from '@/api/hxy'
import store from '@/store'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    user_organize: '',
    user_role: '',
    user_routes: '',
    token_hxy: '',
    hxy_tenant: '',//华栖云系统内租户ID
    hxy_pwd: ''//密码

  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ORGANIZE: (state, organize) => {
    state.user_organize = organize
  },
  SET_ROLE: (state, role) => {
    state.user_role = role
  },
  SET_ROUTES: (state, routes) => {
    state.user_routes = routes
  },

  SET_TOKEN_HXY: (state, token) => {
    state.token_hxy = token
  },
  SET_TENANT_HXY: (state, token) => {
    state.hxy_tenant = token
  },
  SET_PWD: (state, token) => {
    state.hxy_pwd = token
  }

}

//登录认证
const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password }).then(response => {
        const { data } = response
        commit('SET_TOKEN', data.token)
        commit('SET_PWD', password)
        setTokenByName('hxy_pwd', password)
        console.log("登录成功===="+password)

        setToken(data.token)
        // setTokenByName("hxy_pwd",password)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  /***
   * 华栖云登录
   * @param commit
   * @param userInfo
   * @returns {Promise<unknown>}
   */
  // loginHXY({ commit }, userInfo) {
  //   const { username, password, tenant_id } = userInfo
  //   console.log("===="+userInfo)
  //
  //   return new Promise((resolve, reject) => {
  //     resolve()
  //     // loginHXY({ username: username.trim(), password: password, tenant_id: tenant_id }).then(response => {
  //     //   const { params, message, code } = response.data
  //     //   // console.log("hxy==="+JSON.stringify(response))
  //     //   if (message == '登录成功') {
  //     //     console.log('华栖云登录成功：' + message)
  //     //     commit('SET_TOKEN_HXY', params.token)
  //     //     commit('SET_TENANT_HXY', params.info.tenant_id)
  //     //
  //     //     setTokenByName('token_hxy', params.token)
  //     //     setTokenByName('hxy_tenant', params.info.tenant_id)
  //     //     resolve()
  //     //   } else {
  //     //     console.log('华栖云登录失败：' + message)
  //     //     reject('HXY登录失败')
  //     //   }
  //     //
  //     // }).catch(error => {
  //     //   console.log('华栖云登录失败：' + JSON.stringify(error))
  //     //   reject('HXY登录失败')
  //     // })
  //   })
  // },

  loginHXY({ commit, state }, userinfo) {
    return new Promise((resolve, reject) => {
      // logout(state.token).then(() => {

      loginHXY(userinfo).then((response) => {
        const { params, message, code } = response.data
        // console.log("hxy==="+JSON.stringify(response))
        if (message == '登录成功') {
          console.log('华栖云登录成功：' + message)
          commit('SET_TOKEN_HXY', params.token)
          commit('SET_TENANT_HXY', params.info.tenant_id)

          setTokenByName('token_hxy', params.token)
          // setTokenByName('hxy_tenant', params.info.tenant_id)
          resolve(message)
        } else {
          console.log('华栖云登录失败：' + message)
          reject('HXY登录失败')
        }
      }).catch(error => {
        reject('HXY登录失败')
      })
    })
  },

  // get user info 获取用户信息
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {

        console.log('get user info==' + JSON.stringify(response))

        const { data } = response
        if (!data) {
          reject('验证失败，请重新登录.')
        }
        const { name, avatar, organize, routes, roles } = data

        commit('SET_NAME', name)
        commit('SET_AVATAR', avatar)
        commit('SET_ORGANIZE', organize)
        commit('SET_ROUTES', routes)
        commit('SET_ROLE', roles)
        // window.localStorage.setItem("SET_ORGANIZE", data)
        resolve(data)

        // let hxyUser={
        //       account:name,
        //       password:getTokenByName("hxy_pwd"),
        //       tenant_id:organize,
        //       bindcode:name
        // }
        //
        // this.loginHXY(commit,hxyUser).then(response=>{
        //     // this.$global.USER = data;
        //     // console.log("=="+name + ' ' + organize + ' ' + routes + ' ' + roles)
        //     commit('SET_NAME', name)
        //     commit('SET_AVATAR', avatar)
        //     commit('SET_ORGANIZE', organize)
        //     commit('SET_ROUTES', routes)
        //     commit('SET_ROLE', roles)
        //     // window.localStorage.setItem("SET_ORGANIZE", data)
        //     resolve(data)
        //
        // },
        //   ()=>{
        //     reject('HXY验证失败，请重新登录.')
        //   })

      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }, loginfrom) {

    return new Promise((resolve, reject) => {
      // logout(state.token).then(() => {
      logout(loginfrom).then((res) => {
        removeToken() // must remove  token  first
        removeTokenByName('token_hxy')
        resetRouter()
        commit('RESET_STATE')
        resolve(res)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      removeTokenByName('token_hxy')
      removeTokenByName('hxy_tenant')
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

